package softwaretest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import softwaretest.Domain.CameraData;
import softwaretest.Domain.Device;
import softwaretest.repository.CameraDataRepository; // 确保导入CameraData的repository
import softwaretest.repository.DeviceRepository;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;

@Service
public class CameraCaptureService {

    @Autowired
    private TokenCameraService tokenCameraService;

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private CameraDataRepository cameraDataRepository; // 引入CameraData的repository

    private static final String CAPTURE_URL = "https://open.ys7.com/api/lapp/device/capture";

    private final RestTemplate restTemplate = new RestTemplate();

@Scheduled(fixedRate = 60000)
    public void captureImage() {
        // 从数据库获取设备序列号
        Device device = deviceRepository.findFirstByCategory("Camera");
        String deviceSerial = device.getSerialNumber();
        int channelNo = 1;
        int quality = 0;
        // 获取有效的 token
        String token = tokenCameraService.getToken();
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 构建请求参数
        MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
        requestParams.add("accessToken", token);
        requestParams.add("deviceSerial", URLEncoder.encode(deviceSerial, StandardCharsets.UTF_8));
        requestParams.add("channelNo", String.valueOf(channelNo));
        requestParams.add("quality", String.valueOf(quality));
        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestParams, headers);
        // 发送 POST 请求
        ResponseEntity<Map<String, Object>> responseEntity;
        try {
            responseEntity = restTemplate.exchange(
                    CAPTURE_URL, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            throw new RuntimeException("Request failed: " + e.getMessage(), e);
        }
        // 处理响应
        Map<String, Object> responseBody = responseEntity.getBody();
        if (responseBody != null && "200".equals(responseBody.get("code"))) {
            Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
            String picUrl = (String) data.get("picUrl");
            // 下载图片并保存到数据库
            savePictureToDatabase(picUrl, device);
        } else {
            throw new RuntimeException("Failed to capture image: " + responseBody);
        }
    }

    private void savePictureToDatabase(String urlString, Device device) {
        try {
            // 从URL下载图片
            HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 检查响应代码
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = connection.getInputStream()) {
                    byte[] photoData = inputStream.readAllBytes(); // 读取图片数据

                    // 创建CameraData对象并保存到数据库
                    CameraData cameraData = new CameraData();
                    cameraData.setDevice(device);
                    cameraData.setCreatedAt(LocalDateTime.now());
                    cameraData.setPhoto(photoData); // 设置图片数据

                    cameraDataRepository.save(cameraData); // 保存到数据库
                }
            } else {
                System.err.println("Failed to download image. HTTP Response Code: " + connection.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}